<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键词">
                <a-input v-model="queryParam.name" placeholder="请输入关键词" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" icon="plus" @click="onAdd()">新建</a-button>
      </div>
      <s-table
        :row-key="
          (r, i) => {
            return i
          }
        "
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <span slot="status" slot-scope="text, record">
          <template>
            <a-switch
              :checked="text | statusFilter"
              checked-children="开"
              un-checked-children="关"
              @change="changeStatus($event, record.id)"
            ></a-switch>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm title="确认删除该会员等级吗？" @confirm="handleDelete(record)">
              <a-button type="link" size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
      <a-modal
        :title="isNew ? '设置会员' : '编辑会员'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form1">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员等级">
            <a-select
              @change="levelChange"
              v-decorator="['index', { rules: [{ required: true, message: '请选择会员等级' }], initialValue:selectedLevel }]"
            >
              <a-select-option :value="index" :key="index" v-for="index of 100">{{ index }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="等级名称">
            <a-input
              placeholder="等级名称"
              :disabled="false"
              v-decorator="['name', { rules: [{ required: true, message: '请填写等级名称' }] }]"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="等级条件">
            <a-input
              addonBefore="累计完成订单金额满"
              addonAfter="元"
              placeholder="请输入金额"
              type="number"
              v-decorator="['money', { rules: [{ required: true, message: '请输入等级条件', whitespace: true }] }]"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="折扣">
            <a-input
              addonAfter="折"
              placeholder="请输入0.1～10之间的数字"
              type="number"
              v-decorator="[
                'discount',
                { rules: [{ required: true, message: '请输入0.1～10之间的数字', whitespace: true }] },
              ]"
            />
          </a-form-item>
          <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="加速比例">
          <a-input addonAfter="‰" placeholder="请输入加速比例" type="number" v-decorator="['fybili']" />
        </a-form-item> -->
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员等级状态">
            <a-radio-group name="radio" :default-value="selectRadio" @change="radioChange($event)">
              <a-radio :value="'1'">开启</a-radio>
              <a-radio :value="'0'">关闭</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="购买价格">
            <a-input addonAfter="元" placeholder="输入0 会员将不可购买" type="number" v-decorator="['price']" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员图片">
            <storage-select selectNum="1" placeholder="请选择会员图片" type="image" :defaultValue="image" @onOk="onOk">
            </storage-select>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员权益(购买会员关闭)" hasFeedback>
            <a-table
              :columns="columns1"
              :data-source="records.synopsis"
              :row-key="
                (r, i) => {
                  return i
                }
              "
              :pagination="false"
              bordered
            >
              <div slot="name" slot-scope="scope">
                <a-input v-model="scope.title" style="width: 100px"></a-input>
              </div>
              <div slot="icon" slot-scope="scope">
                <storage-select v-model="scope.pic"></storage-select>
              </div>
              <div slot="introduce" slot-scope="scope">
                <a-input v-model="scope.content" style="width: 100px"></a-input>
              </div>
              <div slot="action" slot-scope="scope, record, $index">
                <a-button type="link" style="color: red" @click="del(scope, record, $index)">删除</a-button>
              </div>
            </a-table>
            <a-button block class="editable-add-btn" @click="addSynopsis"> 新增 </a-button>
          </a-form-item>
          <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员权益(购买会员开启)" hasFeedback>
          <a-textarea :rows="2" v-decorator="['detail']" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="购买会员介绍" hasFeedback>
          <a-textarea :rows="2" v-decorator="['buy_prompt']" />
        </a-form-item> -->
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import { getLevelList, updateLevelStatus, updateLevelInfo, deleteLevel } from '@/api/user'
const STATUS = {
  0: false,
  1: true,
}
const columns = [
  {
    title: '等级',
    dataIndex: 'level',
  },
  {
    title: '等级名称',
    dataIndex: 'name',
  },
  {
    title: '折扣',
    dataIndex: 'discount',
  },
  {
    title: '购买所需金额',
    dataIndex: 'price',
  },
  {
    title: '升级条件',
    dataIndex: 'money',
  },
  // {
  //   title: '返佣比例(‰)',
  //   dataIndex: 'fybili',
  // },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]
const columns1 = [
  {
    title: '小标题',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '小标题图标',
    scopedSlots: { customRender: 'icon' },
  },
  {
    title: '小标题介绍',
    scopedSlots: { customRender: 'introduce' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'RechargeList',
  components: {
    STable,
  },
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      form1: this.$form.createForm(this),
      // 表头
      columns,
      columns1,
      image: null,
      selectRadio: null,
      records: {},
      isNew: false,
      selectedLevel: String,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return getLevelList(parameter).then((res) => {
          console.log(res.data)
          res.data.data.forEach((item) => {
            try {
              item.synopsis = JSON.parse(item.synopsis)
            } catch (e) {
              item.synopsis = []
            }
          })
          return res.data
        })
      },
      queryParam: {},
    }
  },
  created() {},
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  methods: {
    resetSearchForm() {
      this.queryParam = {}
    },
    changeStatus: function (value, id) {
      const status = Object.keys(STATUS).find((key) => STATUS[key] === value)
      var params = {
        id: id,
        status: status,
      }
      this.modalLoading = true
      updateLevelStatus(params).then((res) => {
        this.modalLoading = false
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$refs.table.refresh()
          this.$message.success('更新成功！')
        }
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form1.validateFields((err, values) => {
        if (err) {
          return false
        }
        this.modalLoading = true
        var msg = '创建成功'
        var type = 'add'
        if (!this.isNew) {
          values.id = this.records.id
          msg = '编辑成功'
          type = 'edit'
        }
        values.type = type
        values.status = this.selectRadio
        values.level = this.selectedLevel
        values.image = this.image
        values.synopsis = JSON.stringify(this.records.synopsis)
        console.log(values)
        updateLevelInfo(values)
          .then((res) => {
            console.log(res)
            this.modalLoading = false
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success(msg)
              this.visible = false
              this.$refs.table.refresh()
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.modalLoading = false
          })
      })
    },
    handleEdit(record) {
      console.log(record)
      this.visible = true
      this.$nextTick(() => {
        this.form1.setFieldsValue(
          pick(record, ['level', 'name', 'money', 'discount', 'fybili', 'price', 'synopsis', 'detail', 'buy_prompt'])
        )
      })
      this.isNew = false
      this.image = record.image
      console.log(record)
      this.selectedLevel = record.level
      this.selectRadio = record.status
      this.records = record
      console.log(this.records)
    },
    onAdd() {
      this.form1.resetFields()
      this.visible = true
      this.isNew = true
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      deleteLevel({
        id: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('会员等级删除成功')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    radioChange(e) {
      this.selectRadio = e.target.value
    },
    levelChange(value) {
      this.selectedLevel = value
    },
    onOk(val) {
      this.image = val
    },
    addSynopsis() {
      this.records.synopsis.push({
        title: '',
        content: '',
        pic: '',
      })
    },
    del(e, record, index) {
      this.records.synopsis.splice(index, 1)
    },
  },
}
</script>
